﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace KochamPycze.GUI
{
    class ViewModel
    {
        private SoundAnaliser analiser;
        private SoundCapture source;
        private Note ExpectedNote;
        private static Random rnd = new Random();
        
        public DrawingImage Paint { get; set; }
        private DrawingGroup scene;

        internal ViewModel()
        {
            Generate();
            ExpectedNote = new Note(rnd.Next(0, 40), Note.Color.Blue);
            source = new SoundCapture();
            try
            {
                analiser = new SoundAnaliser(source);
            }
            catch (Exception e) { 
                e.Handle();
                System.Environment.Exit(-1);
            }
            analiser.NoteRecognized += Refresh;
            source.Start();
            Refresh();
        }

        private void Generate()
        {
            try
            {
                Paint = new DrawingImage();
                scene = new DrawingGroup();

                ImageDrawing background = new ImageDrawing();
                background.ImageSource = new BitmapImage(new Uri("Background.png", UriKind.Relative));
                background.Rect = new Rect(0, 0, background.ImageSource.Width, background.ImageSource.Height);

                scene.Children.Add(background);

                Paint.Drawing = scene;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void Refresh(Note PlayedNote=null)
        {
            new NoteGlyph(ExpectedNote).Draw(scene);
            if(PlayedNote!=null)
                new NoteGlyph(PlayedNote).Draw(scene);
        }
    }
}
